<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <el-tab-pane label="登录账户设置">
            <!-- 放置表单 -->
            <el-form
              ref="formRef"
              :model="formData"
              :rules="rules"
              label-width="120px"
              style="margin-left: 120px; margin-top:30px"
            >
              <el-form-item label="姓名:" prop="username">
                <el-input v-model="formData.username" style="width:300px" />
              </el-form-item>
              <el-form-item label="密码:" prop="password2">
                <el-input
                  v-model="formData.password2"
                  style="width:300px"
                  type="password"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submit">更新</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="个人详情">
            <!--使用动态组件渲染UserInfo组件-->
            <component :is="UserInfo" />
          </el-tab-pane>
          <el-tab-pane label="岗位信息">
            <component :is="JobInfo" />
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>

// 动态组件
// 【component组件】 通过is属性指定要展示的具体组件名称
import { getUserInfoDetailApi } from '@/api/user'
import { saveUserDetailById } from '@/api/employees'
import UserInfo from '@/views/employees/components/user-info.vue'
import JobInfo from '@/views/employees/components/job-info.vue'

export default {
  components: { UserInfo, JobInfo },
  data() {
    return {
      JobInfo: 'JobInfo',
      UserInfo: 'UserInfo', // 指定userInfo组件的名称字符串，用于component动态组件的渲染
      userId: this.$route.params.id,
      formData: {
        username: '',
        password2: ''
      },
      rules: {
        username: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        password2: [{ required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 9, message: '密码长度6-9位', trigger: 'blur' }]
      }
    }
  },
  created() {
    // 调用获取用户信息的接口
    this.getUserInfo()
  },
  methods: {
    async getUserInfo() {
      // console.log(this.$route)
      const res = await getUserInfoDetailApi(this.userId)
      console.log(res)
      // 获取到的数据填充表单
      this.formData = res
    },
    async submit() {
      //   表单校验
      await this.$refs.formRef.validate()
      await saveUserDetailById({
        ...this.formData,
        // 后端需要的字段的key是password
        // 我们本地数据里面的密码字段的key是password2
        // 所以需要把本地数据的password2赋值给password属性进行提交
        password: this.formData.password2
      })
      // 修改完用户信息之后，重新调用获取用户信息的action，修改全局的用户信息
      this.$store.dispatch('user/getUserInfoAction')
      this.$message.success('更新用户基本信息成功')
    }
  }
}
</script>
